<template>
  <div class="add_bank_account_page" v-loading="pageLoading">
    <div v-if="currentStep === 1">
      <div class="mod">
        <div class="title">
          <i class="icon"></i>
          {{ id ? '编辑银行账户' : '新增银行账户' }}
        </div>
        <div class="content">
          <el-form label-position="right" ref="form" :model="form" :rules="rules" label-width="206px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="开户名称" prop="accountName">
                  <el-input v-model="form.accountName" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="银行账号" prop="bankNumber">
                  <el-input v-model="form.bankNumber"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="开户银行" prop="bankDeposit" key="a">
                  <el-select v-model="form.bankDeposit" style="width: 100%;">
                    <el-option value="">请选择</el-option>
                    <el-option
                      v-for="item in bankList"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">

                <el-form-item label="开户行所在地" prop="bankProvinces">
                  <div class="select_province_city">
                    <el-select v-model="form.bankProvinces" style="width: 50%;" @change="selectProvincesChange">
                      <el-option
                        v-for="item in provinces"
                        :key="item.code"
                        :label="item.name"
                        :value="item.name"
                      >
                      </el-option>
                    </el-select>
                    <el-form-item prop="bankCities" label-width="0" style="width: 50%;margin:0;">
                      <el-select v-model="form.bankCities" style="width: 100%;">
                        <el-option
                          v-for="item in cities"
                          :key="item.code"
                          :label="item.name"
                          :value="item.name"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="开户支行" prop="bankBranch">
                  <el-input v-model="form.bankBranch"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="大额行号（联行号）" prop="bankCode">
                  <el-input v-model="form.bankCode"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="mod btns">
        <el-button class="btn btn_cancel" @click="cancelFn">取消</el-button>
        <el-button type="primary" class="btn btn_sure" v-if="$route.query.status === '2' || $route.query.status === undefined" @click="openDialog">确定</el-button>
        <el-button type="primary" class="btn btn_sure" v-if="$route.query.status === '1'" @click="nextStepClick">下一步</el-button>
      </div>
    </div>
    <div v-if="currentStep === 2">
      <div class="mod company_legal_msg">
        <div class="title">
          <i class="icon"></i>
          企业银行账户
        </div>
        <div
          class="content clearfixed"
        >
          <el-form
            ref="nextStepForm"
            :model="nextStepForm"
            :rules="nextStepRules"
            label-position="right"
            label-width="90px"
            class="company_base_msg_form"
          >
            <el-row type="flex">
              <el-col :span="12" :offset="6">
                <el-form-item label="收小款银行">
                  <el-input
                    :disabled="true"
                    class="w_400"
                    v-model="bankNameAndAccountName"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row type="flex">
              <el-col :span="12" :offset="6">
                <el-form-item label="打款金额" prop="paymentAmount">
                  <div class="small_payment">
                    <el-input v-model="nextStepForm.paymentAmount"></el-input>
                    <el-button
                      type="primary"
                      style="width: 110px;margin-left: 20px;"
                      :loading="sendLoading"
                      @click="getSmallDeposit"
                    >
                      获取小金额
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="big_tips">
            <i class="el-icon-warning icon"></i>
            <div>
              <!-- test -->
              <div class="text">
                小金额将转入
                <span class="theme_color">企业（{{bankNameAndAccountName}}）银行账户</span
                >，请在收支明细中查询，将小额正确输入才可以通过认证。
              </div>
              <div class="text">每天最多下发 5 次，今天已下发 {{ timeInt }} 次</div>
            </div>
          </div>
        </div>

      </div>
      <div class="mod btns">
        <el-button class="btn btn_cancel" @click="prevStepClick">上一步</el-button>
        <el-button type="primary" class="btn btn_sure" :disabled="submitDisabled" @click="submit">提交</el-button>
      </div>
    </div>
    <CustomDialog
      class="dialog"
      title="温馨提示"
      width="50%"
      :visible="dialogVisible"
      :buttonArray="[
        {
          text: '取消',
          clickFn: closeDialog
        },
        {
          text: '确定',
          clickFn: addBank,
          loading: submitLoading
        }
      ]"
      @close="closeDialog"
    >
      <div class="content">
        <el-form
          ref="dialogFrom"
          :model="dialogFrom"
          :rules="dialogRules"
          label-width="100px"
          label-position="right"
        >
          <el-form-item label="手机号码">
            <el-input v-model="createPhonenumber"></el-input>
          </el-form-item>
          <el-form-item label="短信验证码" prop="code">
            <div class="get_code_box">
              <el-input v-model="dialogFrom.code" placeholder="请输入短信验证码"></el-input>
              <el-button
                class="get_code"
                type="primary"
                :loading="codeLoading"
                @click="getCode"
              >{{ sNumber > -1 ? sNumber + 's' : '获取验证码' }}</el-button>
            </div>
          </el-form-item>
        </el-form>
        <!-- <div class="btns">
          <el-button class="btn btn_cancel" @click="closeDialog">取 消</el-button>
          <el-button class="btn btn_sure" type="primary" :loading="submitLoading" @click="addBank">确 定</el-button>
        </div> -->
      </div>
    </CustomDialog>
  </div>
</template>

<script>
import { bankDetail, addBank, editBank, getCode, validateComBankAcc } from '@/api/companyManage'
import { getCityData, getTimeInt, getSmallDeposit } from "@/api/authenticate";
import { getCompanyMsg } from '@/api/production'
import CustomDialog from '@/customComponents/dialog'

export default {
  components: {
    CustomDialog,
  },
  data() {
    return {
      pageLoading: false,
      id: '',
      currentStep: 1,
      bankList: [],
      provinces: [],
      cities: [],
      form: {
        // id: '',
        // user_id: '', // '用户id',
        // enterpriseId: '', // '企业信息id',
        accountName: '', // '开户名称',
        bankNumber: '', // '银行账号',
        bankDeposit: '', // '开户银行',
        bankProvinces: '', // '开户行所在地省',
        bankCities: '', // '开户行所在地市',
        bankBranch: '', // '开户支行',
        bankCode: '', // '大额行号',
        // status: '', //  '状态 1:对公认证账户2:企业账户',
        // create_by: '', // COMMENT '创建者',
        // create_time: '', // '创建时间',
        // update_by: '', // COMMENT '更新者',
        // update_time: '', // '更新时间',
        // remark: '', // '备注',
      },
      rules: {
        // accountName: [{ required: true, trigger: ['change', 'blur'], message: '请输入开记' }], // '开户名称',
        bankNumber: [{ required: true, trigger: ['change', 'blur'], message: '请输入银行账号' }], // '银行账号',
        bankDeposit: [{ required: true, trigger: ['change', 'blur'], message: '请输入银行账号' }], // '开户银行',
        bankProvinces: [{ required: true, trigger: ['change', 'blur'], message: '请输入银行账号' }], // '开户行所在地省',
        bankCities: [{ required: true, trigger: ['change', 'blur'], message: '请输入银行账号' }], // '开户行所在地市',
        bankBranch: [{ required: true, trigger: ['change', 'blur'], message: '请输入银行账号' }], // '开户支行',
        bankCode: [{ required: true, trigger: ['change', 'blur'], message: '请输入银行账号' }], // '大额行号',
        // status: '', //  '状态 1:对公认证账户2:企业账户',
      },
      bankNameAndAccountName: '', //合成的银行和带*号的银行账号
      sendLoading: false,
      nextStepForm: {
        paymentAmount: '', // 打款金额
      },
      nextStepRules: {
        paymentAmount: [{ required: true, trigger: ['change', 'blur'], message: '请输入打款金额' }], // 打款金额
      },
      submitDisabled: false,
      timeInt: 0, // 小金额下发次数
      detailObj: {},
      dialogVisible: false,
      codeLoading: false,
      dialogFrom: {
        code: '',
        uuid: '',
      },
      dialogRules: {
        code: [{ required: true, trigger: ['change', 'blur'], message: '请输入短信验证码' }]
      },
      submitLoading: false,
      createPhonenumber: '',
      sNumber: -1, // 倒计时
      timer: null, // 倒计时
    }
  },
  watch: {
    'detailObj.adminOperation.contactPhone': {
      handler: function(newVal) {
        if (newVal) {
          this.createPhonenumber = newVal?.slice(0, 3) +
              "*".repeat(4) +
              newVal?.slice(-4)
        }
      },
      deep: true,
    }
  },
  mounted() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id
    }
    Promise.all([
      this.getCompanyMsg(), // 根据登录人即可获取，不需要传参
      this.getBankList(),
      this.getCityData(),
    ]).then(() => {
      if (this.$route.query.id) {
        this.getBankDetail()
      }
    })
  },
  methods: {
    getCompanyMsg(){
      return new Promise((resolve, reject) => {
        getCompanyMsg().then((res) => {
          this.detailObj = res.data
          this.form.accountName = res.data.enterpriseName
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    // 获取银行List
    getBankList() {
      return new Promise((resolve, reject) => {
        this.getDicts('peacevisa').then((res) => {
          if (res.code === 200) {
            this.bankList = res.data
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    // 获取省市数据
    getCityData() {
      return new Promise((resolve, reject) => {
        getCityData().then((res) => {
          if (res.code === 200) {
            this.provinces = res.data
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    // 选定省change
    selectProvincesChange(value) {
      this.form.provinces = value
      this.cities = this.provinces?.find?.((item) => {
        if (item.name === value) {
          return item
        }
      })?.children || []
      console.log(this.cities)
    },
    // 获取详情
    getBankDetail() {
      this.pageLoading = true
      bankDetail(this.id).then((res) => {
        this.pageLoading = false
        this.detailObj = res.data
        Object.keys(this.form).forEach((key) => {
          this.form[key] = res.data[key]
        })
      }).catch(() => {
        this.pageLoading = false
      })
    },
    // 取消
    cancelFn() {
      this.$router.back()
    },
    // 打开弹窗
    openDialog() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.dialogVisible = true
        }
      })
    },
    countFn() {
      this.timer = setTimeout(() => {
        if (this.sNumber > -1) {
          --this.sNumber
          this.countFn()
        } else {
          clearTimeout(this.timer)
          this.timer = null
        }
      }, 1000);
    },
    countDown() {
      this.sNumber = 60
      this.countFn()
    },
    getCode() {
      this.codeLoading = true
      // { phonenumber: this.detailObj.adminOperation.contactPhone }
      getCode(3).then((res) => {
        this.codeLoading = false
        this.dialogFrom.uuid = res.uuid;
        this.countDown()
      }).catch(() => {
        this.codeLoading = false
      });
    },
    // 确定
    addBank() {
      const data = {
        ...(this.id ? this.detailObj : {}),
        ...this.form,
        ...(this.id ? {} : this.dialogFrom),
      }
      console.log(data)
      this.$refs.dialogFrom.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          let result
          if (this.id) {
            result = editBank(data)
          } else {
            result = addBank(data)
          }
          result.then((res) => {
            this.submitLoading = false
            this.$message({
              type: 'success',
              message: '提交成功',
              onClose: () => {
                this.$router.back()
              }
            })
          }).catch(() => {
            this.submitLoading = false
          })
        }
      })
    },
    closeDialog() {
      this.dialogVisible = false
      this.dialogFrom.code = ''
      this.dialogFrom.uuid = ''
      this.sNumber = -1
      this.timer = null
      this.$refs.dialogFrom.resetFields()
    },
    prevStepClick() {
      this.currentStep = 1
    },
    // 下一步
    nextStepClick() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 获取小金额剩余次数
          getTimeInt(this.detailObj.id).then((res) => {
            this.timeInt = 5 - res.data
          })
          const bankItem = this.bankList.find((item) => (item.dictValue === this.form.bankDeposit))
          if (bankItem) {
            this.bankNameAndAccountName = ''
            this.bankNameAndAccountName += bankItem.dictLabel + ' '
            this.bankNameAndAccountName += this.form.bankNumber.slice(0,3) +
                                          '*'.repeat(this.form.bankNumber.length-7) +
                                          this.form.bankNumber.slice(-4)

          }
          this.currentStep = 2
        }
      })
    },
    // 获取小金额
    getSmallDeposit() {
      this.sendLoading = true
      getSmallDeposit(this.detailObj.id).then((res) => {
        this.sendLoading = false
        this.submitDisabled = false
        this.timeInt = 5 - res.timeInt
        this.$message({
          type: 'success',
          message: '小金额已发送'
        })
      }).catch(() => {
        this.sendLoading = false
      })
    },
    submit() {
      this.$refs.nextStepForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          validateComBankAcc({
            bankId: this.detailObj.id,
            paymentAmount: this.nextStepForm.paymentAmount,
          }).then(() => {
            // this.submitLoading = false
            const data = {
              ...(this.id ? this.detailObj : {}),
              ...this.form,
              ...(this.id ? {} : this.dialogFrom),
            }
            editBank(data).then((res) => {
              this.submitLoading = false
              this.$message({
                type: 'success',
                message: '提交成功',
                onClose: () => {
                  this.$router.back()
                }
              })
            }).catch(() => {
              this.submitLoading = false
            })
          }).catch(() => {
            this.submitLoading = false
          })
        } else {
          this.$message({
            type: 'error',
            message: '有信息未填',
            duration: 3000
          })
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';

.add_bank_account_page {
  .mod {
    border-radius: 6px;
    box-shadow: 0 1px 2px 0 rgba(1, 24, 70, 0.09);
    background-color: #fff;
    margin-bottom: 16px;
    padding: 20px 0;
    &:last-child {
      margin-bottom: 0;
    }
    .title {
      color: #333;
      font-size: 16px;
      font-weight: 600;
      display: flex;
      align-items: center;
      padding-left: 16px;
      .icon {
        display: block;
        width: 3px;
        height: 16px;
        background-color: $theme;
        margin-right: 5px;
      }
    }
    .content {
      padding: 40px;
      ::v-deep .el-form-item--medium .el-form-item__label {
        font-size: 14px;
        color: #777;
      }
      .select_province_city {
        display: flex;
        justify-content: space-between;
      }
      .small_payment {
        display: flex;
        align-items: center;
      }
      .big_tips {
        margin: 0 20px 20px;
        height: 100px;
        background-color: #fffaf4;
        border-radius: 2px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #f29c1c;
        font-size: 14px;
        .icon {
          font-size: 40px;
          margin-right: 10px;
        }
        .theme_color {
          color: $theme;
        }
        .text {
          line-height: 20px;
        }
      }
    }
    // .no_style_content {
    //   .company_base_msg_form {
    //     margin-top: 60px;
    //     ::v-deep .el-form-item--medium .el-form-item__label {
    //       color: #777;
    //       font-size: 14px;
    //     }
    //     .small_payment {
    //       display: flex;
    //       align-items: center;
    //     }
    //   }
    //   .big_tips {
    //     margin: 0 20px 20px;
    //     height: 100px;
    //     background-color: #fffaf4;
    //     border-radius: 2px;
    //     display: flex;
    //     justify-content: center;
    //     align-items: center;
    //     color: #f29c1c;
    //     font-size: 14px;
    //     .icon {
    //       font-size: 40px;
    //       margin-right: 10px;
    //     }
    //     .theme_color {
    //       color: $theme;
    //     }
    //     .text {
    //       line-height: 20px;
    //     }
    //   }
    // }
  }
  .btns {
    display: flex;
    justify-content: center;
    align-items: center;
    .btn {
      width:  140px;
    }
    .btn_sure {
      margin-left: 40px;
    }
  }
  .dialog {
    font-size: 16px;
    .content {
      .get_code_box {
        display: flex;
        align-items: center;
        .get_code {
          margin-left: 30px;
        }
      }
      .btns {
        margin-top: 70px;
        .btn {
          width: 120px;
        }
        .btn_sure {
          margin-left: 30px;
        }
      }
    }
  }
}
</style>
